<script setup lang="ts">
import type { PropType } from 'vue'
import { getCurrentInstance, nextTick, reactive, ref } from 'vue'
import { ElForm, ElMessage, type FormRules, type UploadRawFile, type UploadRequestOptions } from 'element-plus'
import type { ResultData } from '@/api/base'
// import ClassicEditor from '@ckeditor/ckeditor5-build-classic'
// import { EditorConfig } from '@ckeditor/ckeditor5-core'
// import Editor from '@/build/CkEditorCustom/ckeditor'
// import '@ckeditor/ckeditor5-build-classic/build/translations/zh-cn'
// import dayjs from 'dayjs'
import {
  type addProjectDto,
  addProjectItem,
  type editProjectDto,
  editProjectItem,
  type ProjectResult
} from '@/api/blog'
import MdEditor from '@/components/MdEditor.vue'
import appConfig from '@/config'
import { getToken } from '@/utils/cache'
import { Plus } from '@element-plus/icons-vue'
import { fileUpload } from '@/api/oss'
// import type Vditor from 'vditor'
// 引入富文本组件
const props = defineProps({
  title: {
    default: '对话框',
    type: String as PropType<string>
  },
  width: {
    default: '60%',
    type: [String, Number] as PropType<string | number>
  },
  currentData: {
    type: Object as PropType<ProjectResult>,
    default: () => {}
  },
  isEdit: {
    type: Boolean as PropType<boolean>,
    default: false
  }
})

const accept = 'image/png,image/bmp,image/gif,image/jpeg,image/svg+xml,image/webp'
const beforeUpload = (file: UploadRawFile) => {
  if (accept.indexOf(file.type) === -1) {
    ElMessage({ type: 'error', message: '文件类型错误，不支持的图片格式' })
    return false
  }
  if ((file.size as number) > 100 * 1024 * 1024) {
    ElMessage({ type: 'error', message: '文件大小超过，最大支持 100M' })
  }
  return true
}

const uploadSuccess = (res: any) => {
  console.log(res, res?.code)
  if (res?.code === 200) {
    const fileList = res?.data || []
    if (fileList.length > 0) {
      formData.value.previewUrl = fileList[0].url
    } else {
      ElMessage({ type: 'error', message: res?.msg || '网络异常，请稍后重试' })
    }
  } else {
    ElMessage({ type: 'error', message: res?.msg || '网络异常，请稍后重试' })
  }
}
const emit = defineEmits(['handleRefresh'])
const dialogVisible = ref(false)
const myForm = ref<InstanceType<typeof ElForm>>()
const defaultFormData: ProjectResult = {
  id: '',
  name: '',
  comment: '',
  url: '',
  createDate: '',
  updateDate: '',
  enable: true,
  previewUrl: ''
}
const formData = ref<ProjectResult>(defaultFormData)

const loading = ref(false)

function openDialog() {
  dialogVisible.value = true
}
function closeDialog() {
  beforeDialogClose(() => {})
  dialogVisible.value = false
}
const meEditor = ref<InstanceType<typeof MdEditor>>()

// 保存逻辑
function editSaveHandler() {
  editProjectItem({
    ...formData.value,
    id: formData.value?.id,
    actions: undefined
  } as editProjectDto)
    .then((res: ResultData<any>) => {
      console.log(res)
      if (res?.code === 200) {
        ElMessage({ type: 'success', message: '保存成功' })
        closeDialog()
        nextTick(() => {
          emit('handleRefresh')
        })
      } else {
        ElMessage({ type: 'error', message: res.msg || '网络异常，请稍后重试' })
      }
    })
    .catch((e) => {
      ElMessage({ type: 'error', message: e || '网络异常，请稍后重试' })
    })
    .finally(() => {
      loading.value = false
    })
}

function addSaveHandler() {
  addProjectItem({
    ...formData.value,
    id: undefined,
    createDate: undefined,
    updateDate: undefined,
    actions: undefined
  } as addProjectDto)
    .then((res: ResultData<any>) => {
      if (res?.code === 200) {
        ElMessage({ type: 'success', message: '保存成功' })
        closeDialog()
        nextTick(() => {
          emit('handleRefresh')
        })
      } else {
        ElMessage({ type: 'error', message: res.msg || '网络异常，请稍后重试' })
      }
    })
    .catch((e) => {
      ElMessage({ type: 'error', message: e || '网络异常，请稍后重试' })
    })
    .finally(() => {
      loading.value = false
    })
}

function submitHandler() {
  // console.log('提交')
  nextTick(() => {
    myForm.value!.validate((valid) => {
      if (valid) {
        if (props.isEdit) {
          editSaveHandler()
        } else {
          addSaveHandler()
        }
      }
    })
  })
}

const rules = reactive<FormRules<editProjectDto>>({
  name: {
    required: true,
    message: '项目名不能为空'
  },
  url: {
    required: true,
    message: '链接地址不能为空'
  }
})
function beforeDialogClose(done: Function) {
  myForm.value?.clearValidate()
  formData.value = { ...defaultFormData }
  done()
}

function dialogOpened() {
  myForm.value!.resetFields()
  setTimeout(() => {
    myForm.value!.clearValidate()
    if (props.isEdit) {
      formData.value = {
        ...props.currentData
      } as ProjectResult
    } else {
      formData.value = {
        ...defaultFormData
      }
    }
    getCurrentInstance()?.proxy!.$forceUpdate()
  }, 0)
}

function handleUploadFile(params: UploadRequestOptions): XMLHttpRequest | Promise<unknown> {
  console.log(params)
  const { file } = params
  const formData = new FormData()
  formData.append('file', file)
  return fileUpload(formData).then((res) => {
    uploadSuccess(res)
  })
}

function commentChange(val: string) {
  console.log(val)
}
const mdEditorConfig = {
  height: '100%'
}
defineExpose({
  openDialog
})
</script>

<template>
  <el-dialog
    :title="props.title"
    :close-on-click-modal="false"
    v-model="dialogVisible"
    :width="width"
    top="4vh"
    :before-close="beforeDialogClose"
    @opened="dialogOpened"
  >
    <el-form
      :rules="rules"
      ref="myForm"
      label-width="100px"
      :model="formData"
      class="demo-form-inline"
      v-loading="loading"
    >
      <el-row>
        <el-form-item label="项目名：" prop="name">
          <el-input v-model="formData.name" placeholder="项目名" clearable />
        </el-form-item>
        <el-form-item label="项目地址：" prop="url">
          <el-input
            type="text"
            style="width: 30vw"
            placeholder="请输入项目地址："
            v-model:model-value="formData.url"
          ></el-input>
        </el-form-item>
        <!--        <el-col :span="24">-->
        <!--          <el-form-item label="编辑器类型：" prop="editorType">-->
        <!--            <el-radio-group v-model:model-value="formData.editorType">-->
        <!--              <el-radio :value="1">Markdown编辑器</el-radio>-->
        <!--              <el-radio :value="2">富文本编辑器</el-radio>-->
        <!--            </el-radio-group>-->
        <!--          </el-form-item>-->
        <!--        </el-col>-->
        <el-col :span="24">
          <el-form-item label="项目描述：" prop="comment">
            <MdEditor
              ref="meEditor"
              v-model:model-value="formData.comment"
              height="40vh"
              style="width: 100%"
              :options="mdEditorConfig"
              @update:modelValue="commentChange"
            ></MdEditor>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="6">
          <el-form-item label="可用性：" prop="enable">
            <el-switch v-model="formData.enable"></el-switch>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="项目预览：" prop="enable">
            <el-upload
              action="#"
              :headers="{ Authorization: getToken() }"
              :showFileList="false"
              :accept="accept"
              :before-upload="beforeUpload"
              class="avatar-uploader"
              style="display: inline-block; margin-right: 20px"
              :http-request="handleUploadFile"
            >
              <div
                v-if="formData.previewUrl"
                class="avatar-container"
                style="width: 420px; height: 236px"
                :class="{
                  fitIn: true
                }"
              >
                <img :src="formData.previewUrl" class="avatar img-inner" alt="上传图片" />
              </div>

              <el-icon v-else class="avatar-uploader-icon">
                <Plus />
              </el-icon>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="closeDialog" :loading="loading">取消</el-button>
        <el-button type="primary" @click="submitHandler" :loading="loading"> 保存 </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style scoped lang="scss">
.fe-editor {
  ::v-deep(.el-form-item__content) {
    flex: 0 0 calc(100% - 100px);
  }
  ::v-deep(.tox-tinymce) {
    width: calc(70vw - 140px);
    height: 54vh !important;
  }
}
</style>
